package com.wlz.loadBalance;

import com.wlz.ip.ServerIps;

import java.util.ArrayList;
import java.util.List;

/**
 * @author： wlz
 * @Date 2020/11/20 11:34
 * @description： TODO  权重随机算法
 * @version: 1.0
 */
public class WeightRandom {

    public static String getServer() {
        // 生成一个随机数作为list 的下标
        List<String> ips = new ArrayList<String>();
        for (String ip : ServerIps.WEIGHT_LIST.keySet()) {
            Integer weight = ServerIps.WEIGHT_LIST.get(ip);
            // 按权重进行复制
            for (int i=0; i<weight; i++) {
                ips.add(ip);
            }
        }
        java.util.Random random = new java.util.Random();
        int randomPos = random.nextInt(ips.size());
        return ips.get(randomPos);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(getServer());
        }

    }
}
